package com.dwj.auto.comment.common.security.jwt;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.dwj.auto.comment.common.security.config.SecurityProperties;
import com.dwj.auto.comment.dao.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;

/**
 * @author: dangweijian
 * @description: JWT工具
 * @create: 2020-07-09 09:27
 **/
@Slf4j
@Component
public class JWTTokenHelper {

    @Autowired
    private SecurityProperties securityProperties;

    private static final String ISSUER = "DWJ";
    private static final String AUTHORITIES = "authorities";
    private static final String USER_ROLES = "roles";
    private static final String USER_ID = "id";
    private static final String USERNAME = "username";

    public String createToken(User user){
        String token = Jwts.builder()
                .setId(String.valueOf(user.getId()))
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())
                .setIssuer(ISSUER)
                .claim(AUTHORITIES, JSON.toJSONString(new ArrayList<>()))//自定义属性  权限
                .setExpiration(new Date(System.currentTimeMillis() + securityProperties.getJwtExpiration()))
                .signWith(SignatureAlgorithm.HS512, securityProperties.getJwtSecret())
                .compact();
        token = securityProperties.getJwtTokenPrefix() + token;
        return token;
    }

    public boolean validateToken(String token){
        token = token.replaceAll(securityProperties.getJwtTokenPrefix(),"");
        Claims claims = Jwts.parser().setSigningKey(securityProperties.getJwtSecret()).parseClaimsJws(token).getBody();
        if(MapUtil.isEmpty(claims)){
            return false;
        }
        return true;
    }

    public String getUsername(String token){
        return parser(token).get(USERNAME).toString();
    }

    public String getUserId(String token){
        return parser(token).get(USER_ID).toString();
    }

    public Date getExpiration(String token){
        return parser(token).getExpiration();
    }


    public String getUserRole(String token){
        return parser(token).get(USER_ROLES).toString();
    }

    public String getAuthorities(String token){
        return parser(token).get(AUTHORITIES).toString();
    }

    public Claims parser(String token) {
        return Jwts.parser().setSigningKey(securityProperties.getJwtSecret()).parseClaimsJws(token).getBody();
    }

    public SecurityProperties getSecurityProperties() {
        return securityProperties;
    }
}
